package cn.cntv.app.ipanda.custom;

import com.android.volley.Response;
import com.android.volley.VolleyError;

import cn.cntv.app.ipanda.listener.HandlerListener;
import cn.cntv.app.ipanda.service.HttpService;
import cn.cntv.app.ipanda.service.impl.HttpServiceImpl;


/**
 * @author Xiao JinLai
 * @Date 2015-12-10 12:26
 * @Description 网络请求处理类
 */
public class XjlHandler<T> {

    private static final int ERROR = Integer.MAX_VALUE; //请求错误数值

    private HttpService mService;

    private HandlerListener mListener = null;

    public XjlHandler(HandlerListener listener) {

        mListener = listener;
        mService = new HttpServiceImpl();
    }

    /**
     * 获取 String 型网络数据
     *
     * @param url  请求地址
     * @param what 当前请求标识
     */
    public void getHttpString(String url, final int what) {

        mService.getString(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                HandlerMessage tMessage = new HandlerMessage();
                tMessage.what = what;
                tMessage.obj = response;
                mListener.handlerMessage(tMessage);
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

                HandlerMessage tMessage = new HandlerMessage();
                tMessage.what = ERROR;
                mListener.handlerMessage(tMessage);
            }
        });
    }

    /**
     * 获取 Json 型网络数据
     *
     * @param url  请求地址
     * @param clas 请求实体类
     * @param what 当前请求操作标识
     */
    public void getHttpJson(String url, Class<T> clas, final int what) {

        mService.getJson(url, clas, new Response.Listener<T>() {
            @Override
            public void onResponse(T response) {

                HandlerMessage tMessage = new HandlerMessage();
                tMessage.what = what;
                tMessage.obj = response;
                mListener.handlerMessage(tMessage);
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

                HandlerMessage tMessage = new HandlerMessage();
                tMessage.what = ERROR;
                mListener.handlerMessage(tMessage);
            }
        });
    }


}
